<template>
  <div>
    <el-container class="container-box">
      <el-container class="">
        <el-header class="container-header">
          <el-tabs id="p20" type="border-card" v-model="activeName">
            <el-tab-pane :lazy="true" :name="TABSNAME.public" label="公开专题"></el-tab-pane>
            <!-- <el-tab-pane :lazy="true" :name="TABSNAME.team" label="团队专题"></el-tab-pane>
            <el-tab-pane :lazy="true" :name="TABSNAME.evaluation" label="历年真题"></el-tab-pane>
            <el-tab-pane :lazy="true" :name="TABSNAME.preliminaryTest" label="初试专题"></el-tab-pane>
            <el-tab-pane :lazy="true" :name="TABSNAME.myQuestionBank" label="我的专题"></el-tab-pane> -->
            <!-- 搜索条件 -->
            <div class="container-header-form">
              <div v-if="tabsQueryCfg[activeName].desc">
                <!-- <div class="font-size14 icon-text">
                  <el-icon>
                    <InfoFilled />
                  </el-icon>
                  &nbsp;专题说明
                </div> -->
                <div>
                  <el-text size="small" type="info">
                    <el-icon>
                      <InfoFilled />
                    </el-icon>
                    {{ tabsQueryCfg[activeName].desc }}
                  </el-text>
                </div>
              </div>
              <el-form class="" label-position="left">
                <el-form-item class="container-header-form-item" size="default" label="查找专题" :label-width="70">
                  <div class="container-header-form-item-flex">
                    <div>
                      <el-input size="default" :style="{ width: '250px' }" v-model.lazy="_formInline.name"
                        placeholder="输入查找专题名">
                      </el-input>
                      <el-button class="container-header-form-search-btn" @click="search" type="primary" size="default">
                        搜索
                      </el-button>
                    </div>
                    <router-link v-if="activeName == TABSNAME.myQuestionBank && getuser?.isAdmin" custom
                      :to="{ name: '修改我的专题', params: { ID: 0 } }" v-slot="{ navigate }">
                      <el-button @click="navigate" type="primary" size="default">+ 创建我的专题</el-button>
                    </router-link>
                    <div v-if="activeName == TABSNAME.team && getuser?.isAdmin">
                      <el-button @click="dialogVisible = true" type="primary" size="default">+ 导入团队专题</el-button>
                    </div>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </el-tabs>
        </el-header>
        <el-main class="container-content">
          <el-scrollbar>
            <el-table row-class-name="cursor-pointer" :data="getquestionbank" stripe v-loading="loading" width="100%"
              @row-click="rowClick">
              <template v-slot:empty>
                <el-empty image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png" />
              </template>
              <el-table-column width="100" prop="ID" label="编号" />
              <el-table-column show-overflow-tooltip width="" prop="name" label="题单" />
              <el-table-column width="" prop="questionlabel" label="包含题目标签">
                <template #default="{ row, column }">
                  <el-tag class="question-intable-label" text type="primary" effect="plain" size="default"
                    v-for="(vo, keys) in row.questionlabel" v-text="getlabel.find(e => e.ID === vo.labelid)?.name"
                    :key="`1-${keys}`">
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column width="120" prop="questionquestionbank" align="center" label="题单题目数">
                <template #default="{ row, column }">
                  {{ row.questionquestionbank?.length }}
                </template>
              </el-table-column>
              <el-table-column width="130" prop="count" align="center" label="我提交的题目数" />
              <el-table-column v-if="activeName !== TABSNAME.preliminaryTest" width="200" prop="ACcount" label="我的通过率">
                <template #default="{ row, column }">
                  <el-progress :text-inside="true" :stroke-width="18" :percentage="getACRate(row)"
                    :color="customColors" />
                </template>
              </el-table-column>
              <el-table-column fixed="right" width="160" prop="" v-if="activeName === TABSNAME.myQuestionBank"
                label="操作">
                <template #default="{ row, column }">
                  <router-link custom :to="{ name: '修改我的专题', params: { ID: row.ID } }" v-slot="{ navigate }">
                    <el-button size="default" type="primary" @click.stop="navigate">编辑</el-button>
                  </router-link>
                  <el-button size="default" type="primary" @click.stop="del(row.ID)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination class="pager" size="default" :page-size="limit" :total="getquestionbankcount"
              @current-change="changePage" layout="total,prev, pager, next"
              :current-page="Math.floor(offset / limit) + 1">
            </el-pagination>
          </el-scrollbar>
        </el-main>
      </el-container>
    </el-container>
    <!-- 导入团队专题 -->
    <el-dialog v-model="dialogVisible" v-if="dialogVisible" title="选择专题" width="840px" height="90vh" top="0"
      :before-close="beforeClose">
      <template #header>
        <span class="icon-text el-dialog__header-title">
          <el-icon class="text-primary">
            <Guide />
          </el-icon>
          选择专题
        </span>
      </template>
      <Addselectquestionbank :addclick="addclick" :teamid="teamId">
      </Addselectquestionbank>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import { uniqBy } from "lodash-es";
import { assign, debounce } from "underscore";
import { computed, onMounted, reactive, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { Iobj, asyncaddquestionbankteam, asyncdelquestionbank, asyncgetmyquestionbank, asyncselectquestionbank, asyncselectquestionlabel } from "../../api/index";
import { Storekey } from "../../interface";
import Studycodemodel from "../../mysql_interface/studycodemodel";
import Addselectquestionbank from "../../ojSass/views/Questionbank/addselectquestionbank.vue";

// tabs
enum TABSNAME {
  public = "public",
  team = "team",
  evaluation = "evaluation", // 历年真题
  preliminaryTest = "preliminaryTest", // 初试专题
  myQuestionBank = "myQuestionBank", // 我的专题
}

// tabs 切换 参数配置
const tabsQueryCfg = {
  [TABSNAME.public]: {
    isteam: 0, usertype: 'user', purpose: '', order: 'top', sortable: 'asc', istest: 0,
    desc: "公开专题：该专题是系统公开专题，所有人都可以访问"
  },
  [TABSNAME.team]: {
    isteam: 1, istest: 0,
    desc: "团队专题：该专题是团队内部指定专题，由团队管理员从“我的专题”中授权开放至团队"
  },
  [TABSNAME.evaluation]: {
    purpose: '能力测评', isteam: 0, order: 'ID', sortable: 'asc', istest: 1,
    desc: "历年真题：往年CSP/NOIP真题，可作为赛前模拟"
  },
  [TABSNAME.preliminaryTest]: {
    purpose: '初试练习', isteam: 0, order: 'ID', sortable: 'asc', istest: 0,
    desc: "初试专题：适合CSP/NOIP第一轮的初试题目，以知识点分类汇总"
  },
  [TABSNAME.myQuestionBank]: {
    desc: "我的专题：用于我个人收藏的专题。如果是团队管理员，可以将我的专题开放至团队"
  },
}

// AC 率颜色
const customColors = [
  { color: '#e83828', percentage: 20 },
  { color: '#f0830ac', percentage: 40 },
  { color: '#82bd1c', percentage: 60 },
  { color: '#1ecbb4', percentage: 80 },
  { color: '#4683fa', percentage: 100 },
]

const store = useStore(Storekey)
const router = useRouter()
const route = useRoute()
const loading = ref(true)

const getlabel = computed(() => {
  return store.state.label?.rows || []
})
const getteam = computed(() => {
  return store.state.team?.rows || []
})
const getuser = computed(() => {
  return store.state.user
})
const teamId = computed(() => {
  return Number(getuser.value?.teamid)
})
const isteam = computed({
  get() {
    return Number(route.query.isteam || 0)
  },
  set(y: number) {
    router.push({ query: { order: "top", offset: 0, limit: 20, isteam: y, }, });
  },
})
const offset = ref(0)
const limit = ref(20)
const sortable = computed(() => {
  return String(route.query.sortable || 'asc')
})
const order = computed(() => {
  return String(route.query.order || 'top') as keyof Studycodemodel.Iquestionbank
})
// 重置参数
function reset() {
  offset.value = 0
}
const activeName = ref<TABSNAME>(TABSNAME.public)
watch(() => activeName.value, (e) => {
  let tmp = Object.assign({}, tabsQueryCfg[e])
  // 删除描述
  delete tmp.desc
  router.push({ query: assign({}, tmp) })
  reset()
  start()
})
const tabName = computed(() => {
  return route.query.tabName as TABSNAME
})
function search() {
  start();
}
onMounted(() => {
  // 是否从首页跳转
  if (tabName.value) {
    activeName.value = TABSNAME[tabName.value]
  }
  start()
})

const _formInline = reactive<Iobj<Studycodemodel.Iquestionbank>>({ teamid: [], name: "", label: "", })
watch(_formInline, (e) => {
  router.push({ query: assign({}, route.query, { order: "top", offset: 0, limit: 20, }), })
})
const formInline = computed(() => {
  const I: Iobj<Studycodemodel.Iquestionbank> = {
    _order: order.value,
    _offset: offset.value,
    _sortable: sortable.value || 'ASC',
    _limit: limit.value,
  }
  if (route.query.purpose) {
    I.purpose = route.query.purpose
  }
  if (_formInline.name) {
    // 判断输入的是id还是题单名
    if (_formInline.name == Number(_formInline.name)) {
      I._like = ['ID', _formInline.name]
    } else {
      I._like = ['name', _formInline.name]
    }
  }
  // usertype 只区分 public 和 team
  let usertype = TABSNAME.public;
  if (isteam.value || activeName.value === TABSNAME.team) {
    usertype = TABSNAME.team;
    I.teamid = teamId.value ? teamId.value : getteam.value.map((v) => v.ID)
  }
  I.usertype = usertype
  return I
})
watch(formInline, (e) => {
  start()
})
async function start() {
  await debouncet1.value()
}
const getquestionbank = ref<Studycodemodel.Iquestionbank[]>([])
const getquestionbankcount = ref(0)
const debouncet1 = ref(debounce(async () => {
  loading.value = true;
  try {
    if (activeName.value === TABSNAME.myQuestionBank) {
      let cond = { ...formInline.value }
      delete cond.usertype
      const { rows, count } = await asyncgetmyquestionbank(cond);
      getquestionbank.value = rows
      getquestionbankcount.value = count
    } else {
      const { rows, count } = await asyncselectquestionbank(formInline.value);
      getquestionbank.value = rows
      getquestionbankcount.value = count
    }
    getquestionbank.value = await formatterData(getquestionbank.value)

  } catch (e) {
    console.error("catch error=>", e)
  }
  loading.value = false;
}, 300))

// 获取题单
async function formatterData(data: Studycodemodel.Iquestionbank[]) {
  const questions = data.map(t => t.questionquestionbank?.map(f => f.questionid)).flat()
  const questionlabels = await asyncselectquestionlabel({ questionid: questions, })
  return data.map(e => {
    const { questionquestionbank } = e
    const questionlabel = questionquestionbank?.map(t => {
      const { questionid } = t
      return questionlabels.rows.filter(t => t.questionid === questionid)
    }).flat() || []
    return assign(e, { questionlabel: uniqBy(questionlabel, e => e.labelid) })
  })
}

async function del(ID?: number) {
  if (ID) {
    ElMessageBox.confirm("你确定要删除此题吗", "提示").then(async () => {
      try {
        await asyncdelquestionbank({ ID });
        ElMessage.success("删除成功");
        start();
      } catch (e: any) {
        ElMessage.error(e);
      }
    });
  }
}

function changePage(r: number) {
  offset.value = (r - 1) * limit.value
}
// AC率
function getACRate(row: Studycodemodel.Iquestionbank) {
  return row.questionquestionbank?.length ? Math.floor(Number(row.ACcount || 0) / Number(row.questionquestionbank?.length) * 100) : 0
}
function rowClick(row: Studycodemodel.Iquestionbank) {
  router.push({ name: '题库列表', params: { ID: row.ID }, query: { istest: route.query.istest } })
}

// 添加团队专题
const dialogVisible = ref(false)
async function addclick(v: Studycodemodel.Iquestionbank) {
  await asyncaddquestionbankteam({ questionbankid: v.ID, teamid: teamId.value }).then(() => {
    dialogVisible.value = false
    ElMessage.success('添加成功')
  }).catch(f => {
    ElMessage.error(f)
  })
}

function beforeClose() {
  start()
  dialogVisible.value = false
}
</script>

<style scoped>
.container-box {
  padding: var(--container-margin) 5% 0;
  margin: var(--container-margin) 0rem 0 0rem;
  /* 外边距 */
  --container-margin: 20px;
  --container-header-height: 16vh;
  --container-bg-color: #fff
}

.container-header {
  /* margin-top: var(--container-margin); */
  height: var(--container-header-height);
  min-height: var(--container-header-height);
  width: 100%;
  padding: 0;

  box-shadow: var(--container-box-shadow);
}

.container-header-form {
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  /* height: calc(var(--container-header-height) - var(--el-tabs-item-height)); */
  height: auto;
  padding: 10px 0 15px 0;
}

.container-header-form-item {
  font-weight: 700;
  text-align: left;
  margin: 10px 0;
  --color-43: #000;
}

.container-header-form-item .el-button.is-text {
  border-width: 1px;
}

.container-header-form-item .el-button--default:active {
  border-color: transparent
}

.container-header-form-item-flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.container-content {
  margin-top: var(--container-margin);
  background: var(--container-bg-color);
  padding: var(--container-margin);
  min-width: 80%;
}

.container-content .pager {
  margin: var(--container-margin);
  margin-right: 0;
  margin-bottom: 0;
  float: right;
}
</style>

<style>
.bg-43 {
  background-color: var(--color-43) !important;
  color: #ffffff !important;
  border-radius: 0px 2px 2px 0px !important;
}

#tabs .el-tabs__item {
  height: 50px !important;
  line-height: 50px;
}
</style>